﻿using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace JH
{
    /// <summary>
    ///  获取从当前Transform到根节点的路径
    /// </summary>
    public static class GetRootPath
    {
        /// <summary>
        ///  获取从当前Transform到根节点的路径
        /// </summary>
        public static string GetRootPathStringWithSiblingIndexEm(this Transform transform, bool includeSelf = false,
            bool fromRoot = true)
        {
            if (!transform) return null;
            return string.Join("/", GetRootPathListEm(transform, includeSelf, fromRoot)
                .Select(i => i.name + i.GetSiblingIndex()).ToList());
        }
        
        /// <summary>
        ///  获取从当前Transform到根节点的路径
        /// </summary>
        public static string GetRootPathStringEm(this Transform transform, bool includeSelf = false,
            bool fromRoot = true)
        {
            if (!transform) return null;
            return string.Join("/", GetRootPathListEm(transform, includeSelf, fromRoot)
                .Select(i => i.name).ToList());
        }

        /// <summary>
        ///  获取从当前Transform到根节点的路径
        /// </summary>
        public static List<Transform> GetRootPathListEm(this Transform transform, bool includeSelf = false,
            bool fromRoot = true)
        {
            if (!transform) return new List<Transform>();
            var path = new List<Transform>();
            var current = includeSelf ? transform : transform.parent;
            while (current)
            {
                path.Add(current);
                current = current.parent;
            }

            if (fromRoot) path.Reverse();
            return path;
        }
    }
}